import tkinter as tk
from PIL import Image, ImageDraw

# 初始化数据
ls = [
    {'id': 1, 'name': '王昭东'},
    {'id': 2, 'name': '王德俊'},
    {'id': 3, 'name': '李秀兰'},
    {'id': 4, 'name': '王昭名'}
]

kg = [
    {'source': 1, 'target': 2, 'relation': '父子'},
    {'source': 1, 'target': 3, 'relation': '母子'},
    {'source': 1, 'target': 4, 'relation': '兄弟'},
    {'source': 2, 'target': 1, 'relation': '父子'},
    {'source': 2, 'target': 3, 'relation': '夫妻'},
    {'source': 2, 'target': 4, 'relation': '父子'},
    {'source': 3, 'target': 1, 'relation': '母子'},
    {'source': 3, 'target': 2, 'relation': '夫妻'},
    {'source': 3, 'target': 4, 'relation': '母子'},
    {'source': 4, 'target': 1, 'relation': '兄弟'},
    {'source': 4, 'target': 2, 'relation': '父子'},
    {'source': 4, 'target': 3, 'relation': '母子'}
]

# 设置画布参数宽度、高度、半径、行高
w = 600 
h = 300
r = 50
l = 10

def run():
    # 返回数据
    id = int(node_id.get())
    ls = eval(ls_text.get(1.0,tk.END))
    kg = eval(kg_text.get(1.0,tk.END))
    print(ls,kg)
    # 清空画布
    canvas.delete("all")
     # 绘制主节点
    canvas.create_oval(w / 2 - r, l, w / 2 + r, 2*r + l, outline="#000", fill="#FFF")
    canvas.create_text(w / 2, r + l, text=get_name(ls, id), fill="#000", font=("幼圆", 14))

    # 返回符合要求的节点
    all = get_kg(kg,id)
    num = len(all)
    for i in range(num):
        # 坐标点
        x = w / num * (i + 1) - w / num / 2
        y = num * r + l
        # 绘制椭圆形
        canvas.create_oval(x - r, y - r / 2, x + r, y + r / 2, outline="#000")
        # 绘制文字
        canvas.create_text(x, y + l, text=get_name(ls, all[i]['target']), fill="#000", font=("幼圆", 14))
        # 绘制线条
        canvas.create_line(x, y, w / 2, r + l, fill="#000")
        # 绘制关系
        xx = x + (w / 2 - x) / 2
        yy = r + l + (y - r - l) / 2
        canvas.create_text(xx, yy + l, text=all[i]['relation'], fill="#000", font=("幼圆", 14))
    
# 返回名称
def get_name(ls, key):
    for i in ls:
        if i['id'] == key:
            return i['name']
        
# 返回数组
def get_kg(ls, key):
    data = []
    for i in ls:
        if i['source'] == key:
            data.append(i)
    return data    


# 创建主窗口
root = tk.Tk()
root.title("知识图谱")

# ID选择区域
frame1 = tk.Frame(root)
frame1.pack()
node_label = tk.Label(frame1, text="主节点ID:")
node_label.pack(side="left")
node_id = tk.Entry(frame1)
node_id.pack(side="left")
node_id.insert(0,1)
generate_button = tk.Button(frame1, text="生成图谱", command=run)
generate_button.pack(side="left")
# 数据输入区域
ls_text = tk.Text(root, width=50, height=14)
ls_text.pack(fill=tk.BOTH, expand=True)
ls_text.insert(1.0,str(ls))
kg_text = tk.Text(root, width=50, height=14)
kg_text.pack(fill=tk.BOTH, expand=True)
kg_text.insert(1.0,str(kg))

# 画布区域
canvas = tk.Canvas(root, width=w, height=h, bg="#FFF")
canvas.pack(expand=True)

# 运行主循环
root.mainloop()